package com.common.zrd.json;

import lombok.Data;

import java.io.Serializable;

/**
 * author: zrd
 *
 * @Date: 2019/11/4 15:15
 * @Description: 公共JSON返回类
 */
@Data
public class CommonJsonResult<T> implements Serializable {
    public static final int SUCCESS = 200;
    public static final int ERROR = 500;
    private static final long serialVersionUID = 3417070568933266620L;

    /**
     * 返回是否成功的状态, 0表示成功,
     * 1或其他值 表示失败
     */
    private int code;
    /**
     * 成功时候,返回的JSON数据
     */
    private T data;
    /**
     * 是错误时候的错误消息
     */
    private String msg;

    public CommonJsonResult() {
        this.code = SUCCESS;
        this.msg = "执行成功";
    }

    /**
     * @return
     * @Author zrd
     * @Description
     * @Date 15:21 2019/11/4
     * @Param
     **/
    public CommonJsonResult(int code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }

    public CommonJsonResult(int code, T data) {
        this.code = code;
        this.data = data;
    }

    public CommonJsonResult(Throwable e) {
        this.code = ERROR;
        this.data = null;
        this.msg = e.getMessage();
    }

    public CommonJsonResult(T data) {
        this.code = SUCCESS;
        this.data = data;
        this.msg = "执行成功！";
    }

    public static <T> CommonJsonResult<T> of(T body) {
        return new CommonJsonResult(body);
    }

    public static <T> CommonJsonResult<T> empty() {
        return new CommonJsonResult();
    }

    public static <T> CommonJsonResult<T> failed(int code, String desc) {
        return new CommonJsonResult(code, null, desc);
    }

    public static <T> CommonJsonResult<T> error(int code, T body, String desc) {
        return new CommonJsonResult(code, body, desc);
    }


    @Override
    public String toString() {
        return "JsonResult [code=" + this.code + ", data=" + this.data + ", message=" + this.msg + "]";
    }


}
